package com.ebo.learn_demo.view

import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.Recycler
import com.ebo.learn_demo.leo_slidecard.CardConfig

/**
 * @author zmp
 * @date : 2022/1/20 15:09
 * des:MySlideLayoutManager
 */
class MySlideLayoutManager : RecyclerView.LayoutManager() {


    override fun generateDefaultLayoutParams(): RecyclerView.LayoutParams {
        return RecyclerView.LayoutParams(
            RecyclerView.LayoutParams.WRAP_CONTENT,
            RecyclerView.LayoutParams.WRAP_CONTENT
        )
    }


    override fun onLayoutChildren(recycler: RecyclerView.Recycler, state: RecyclerView.State?) {
        //1 . ViewHolder 复用
        detachAndScrapAttachedViews(recycler)
        val bottomPosition: Int
        val itemCount = itemCount
        bottomPosition = if (itemCount < CardConfig.MAX_SHOW_COUNT) {
            0
        } else {
            itemCount - CardConfig.MAX_SHOW_COUNT
        }

        for (i in bottomPosition until itemCount) {
            //2 .复用
            val view = recycler.getViewForPosition(i)

            addView(view)
            measureChildWithMargins(view, 0, 0)
            val widthSpace = width - getDecoratedMeasuredWidth(view)
            val heightSpace = height - getDecoratedMeasuredHeight(view)

            // 布局 ---draw -- onDraw ,onDrawOver, onLayout
            layoutDecoratedWithMargins(
                view, widthSpace / 2, heightSpace / 2,
                widthSpace / 2 + getDecoratedMeasuredWidth(view),
                heightSpace / 2 + getDecoratedMeasuredHeight(view)
            )

            val level = itemCount - i - 1
            if (level > 0) {
                if (level < CardConfig.MAX_SHOW_COUNT - 1) {
                    view.translationY = (CardConfig.TRANS_Y_GAP * level).toFloat()
                    view.scaleX = 1 - CardConfig.SCALE_GAP * level
                    view.scaleY = 1 - CardConfig.SCALE_GAP * level
                } else {
                    // 最下面的那个view 与前一个view 布局一样
                    view.translationY = (CardConfig.TRANS_Y_GAP * (level - 1)).toFloat()
                    view.scaleX = 1 - CardConfig.SCALE_GAP * (level - 1)
                    view.scaleY = 1 - CardConfig.SCALE_GAP * (level - 1)
                }
            }
        }
    }


    override fun scrollHorizontallyBy(
        dx: Int, recycler: Recycler?,
        state: RecyclerView.State?
    ): Int {
        return dx
    }

    /**
     * {@inheritDoc}
     */
    override fun scrollVerticallyBy(
        dy: Int, recycler: Recycler?,
        state: RecyclerView.State?
    ): Int {
        return dy
    }

    /**
     * SCROLL_STATE_IDLE
     */
    override fun onScrollStateChanged(state: Int) {
        super.onScrollStateChanged(state)
    }

}